#include "messageshowarea.h"
#include <QScrollArea>
#include <QPainter>
#include <QPainterPath>
#include <QScrollBar>
#include <QLabel>
#include <QVBoxLayout>
#include <QGridLayout>
#include <QPushButton>
#include "debug.h"
#include "model/data.h"
#include "userinfowindow.h"
#include "mainwidget.h"

using namespace model;
MessageShowArea::MessageShowArea() {

    //开启滑动属性
    this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    setWidgetResizable(true);
    this->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { height: 0px}");
    this->verticalScrollBar()->setStyleSheet(
        "QScrollBar:vertical {"
        "    border: none;"
        "    background: #f1f1f1;"  // 滚动条轨道颜色
        "    width: 6px;"         // 稍微宽一点更易点击
        "    margin: 0px 0px 0px 0px;"
        "}"
        "QScrollBar::handle:vertical {"
        "    background: #c1c1c1;" // 滚动条手柄颜色
        "    min-height: 20px;"    // 最小高度
        "    border-radius: 3px;"  // 圆角
        "}"
        "QScrollBar::handle:vertical:hover {"
        "    background: #a8a8a8;" // 悬停颜色
        "}"
        "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {"
        "    height: 0px;"         // 隐藏上下箭头
        "    background: none;"
        "}"
        "QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {"
        "    background: none;"
        "}"
        );
    //设置内部的容器
    container = new QWidget();
    this->setWidget(container);
    //添加布局管理器
    QVBoxLayout* layout = new QVBoxLayout();
    layout->setSpacing(0);
    layout->setContentsMargins(20, 0, 0, 0);
    container->setLayout(layout);


#if TEST_UI
    UserInfo userInfo;
    userInfo.userId = QString::number(1000);
    userInfo.nickName = "张三";
    userInfo.description = "从今天开始认真敲代码";
    userInfo.icon = QIcon(":/resource/images/avatar2.png");
    userInfo.phone = "18612345678";
    Message message = Message::makeMessage(TEXT_TYPE, "", userInfo, QString("这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息这是一条测试消息").toUtf8(), "");
    this->addMessage(false, message);

    for (int i = 1; i <= 30; ++i) {
        UserInfo userInfo;
        userInfo.userId = QString::number(1000 + i);
        userInfo.nickName = "张三" + QString::number(i);
        userInfo.description = "从今天开始认真敲代码";
        userInfo.icon = QIcon(":/resource/images/avatar.jpg");
        userInfo.phone = "18612345678";
        Message message = Message::makeMessage(TEXT_TYPE, "", userInfo, QString("这是一条测试消息").toUtf8(), "");
        this->addMessage(rand() % 2, message);
    }

#endif
}

void MessageShowArea::addMessage(bool isLeft, const Message &message)
{
    MessageItem* item = MessageItem::makeMessageItem(isLeft, message);
    container->layout()->addWidget(item);
}

void MessageShowArea::insertMessage(bool isLeft, const Message &message)
{
    MessageItem* item = MessageItem::makeMessageItem(isLeft, message);
    QVBoxLayout* layout = dynamic_cast<QVBoxLayout*>(container->layout());
    layout->insertWidget(0, item);
}

void MessageShowArea::clear()
{
    // 遍历布局管理器, 删除里面的元素
    QLayout* layout =container->layout();
    for(int i = layout->count() - 1; i >= 0 ; i--)
    {
        QLayoutItem* item = layout->takeAt(i);
        if(item != nullptr && item->widget() != nullptr)
        {
            delete item->widget();
        }
    }
}

MessageItem::MessageItem(bool isLeft)
    :isLeft(isLeft)
{
}

MessageItem *MessageItem::makeMessageItem(bool isLeft, const Message &message)
{
    MessageItem* messageItem = new MessageItem(isLeft);
    //网格布局
    QGridLayout* layout = new QGridLayout();
    layout->setSpacing(10);
    layout->setContentsMargins(10 ,10, 40 , 0);
    messageItem->setMinimumHeight(100);
    messageItem->setLayout(layout);

    //头像Btn
    QPushButton* avatarBtn = new QPushButton();
    avatarBtn->setFixedSize(QSize(40, 40));
    avatarBtn->setIconSize(QSize(40, 40));
    avatarBtn->setIcon(message.sendr.icon);


    if(isLeft){
        layout->addWidget(avatarBtn, 0, 0, 2, 1, Qt::AlignLeft | Qt::AlignTop);
    }else
    {
        layout->addWidget(avatarBtn, 0, 1, 2, 1, Qt::AlignLeft | Qt::AlignTop);
    }

    //昵称和时间
    QLabel* infoLabel = new QLabel();
    QString info  = message.sendr.nickName + " | " + message.time;
    infoLabel->setText(info);
    infoLabel->setAlignment(Qt::AlignBottom); //靠下排布
    infoLabel->setStyleSheet("QLabel {font-size: 12px; color: rgb(180, 180, 180);}");
    if(isLeft)
    {
        layout->addWidget(infoLabel, 0, 1, 1, 1);
    }
    else
    {
        layout->addWidget(infoLabel, 0, 0, 1, 1, Qt::AlignRight);
    }

    //消息展示区, 自定义适应消息的长短
    QWidget* contentLabel = makeTextMessageItem(isLeft, message.content);
    if(isLeft)
    {
        layout->addWidget(contentLabel, 1, 1);
    }
    else
    {
        layout->addWidget(contentLabel, 1, 0);
    }

    // 构建消息的时候连接槽函数
    connect(avatarBtn, &QPushButton::clicked, messageItem, [=](){
        MainWidget* mainWidget = MainWidget::getInstance(); // 注意获取单例的时机
        UserInfoWindow* userInfoWindow = new UserInfoWindow(mainWidget, message.sendr);
        userInfoWindow->exec();
    });
    return messageItem;
}

QWidget *MessageItem::makeTextMessageItem(bool isLeft, const QString &text)
{
    MessageContentLabel* label = new MessageContentLabel(text, isLeft);
    return label;
}


MessageContentLabel::MessageContentLabel(const QString& text, bool isLeft)
    : isLeft(isLeft)
{
    //设置setpolicy不然Qt到时候会均匀分配
    this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    QFont font;
    font.setFamily("微软雅黑");
    font.setPixelSize(16);

    label = new QLabel(this);
    label->setText(text);
    label->setFont(font);
    label->setWordWrap(true); //设置自动换行
    label->setAlignment(Qt::AlignCenter | Qt::AlignLeft);
    label->setStyleSheet("QLabel {padding: 0 10px; line-height: 1.2; background-color: transparent;}");
}

void MessageContentLabel::paintEvent(QPaintEvent *event)
{
    (void)event;
    //底层绘制接口
    //首先通过文本长度获取绘制圆角矩形的宽高，然后再绘制

    //获取父对象的宽度， 默认超过父元素的60就换行
    QObject* object = this->parent();
    if(!object->isWidgetType()) return;

    QWidget* parent = dynamic_cast<QWidget*>(object);
    int width = parent->width() * 0.6;

    //获取文本的总长度（尺寸）
    QFontMetrics* fm = new QFontMetrics(label->font());
    int totalWidth = fm->horizontalAdvance(label->text());

    //计算row
    int row = (totalWidth / (width - 40)) + 1;

    //文本较短
    if(row == 1) width = totalWidth + 40;

    //计算高度
    int height = 20 + (label->font().pixelSize() * 1.2) * row;

    //开始绘制
    QPainter painter(this);
    QPainterPath painterPath;
    //设置抗锯齿
    painter.setRenderHint(QPainter::Antialiasing);
    if(isLeft)
    {
        painter.setPen(QPen(QColor(255, 255, 255)));
        painter.setBrush(QColor(255, 255, 255));

        painter.drawRoundedRect(10 , 0 , width , height , 10 , 10);
        //绘制箭头
        painterPath.moveTo(10, 15);
        painterPath.lineTo(0, 20);
        painterPath.lineTo(10, 25);
        painterPath.closeSubpath();
        painter.drawPath(painterPath);

        //移动label
        label->setGeometry(10, 0, width, height);
    }
    else
    {
        painter.setPen(QPen(QColor(137, 217, 97)));
        painter.setBrush(QColor(137, 217, 97));

        int leftPos = this->width() - width - 10;
        int rightPos = this->width() - 10;
        painter.drawRoundedRect(leftPos, 0, width, height, 10, 10);

        painterPath.moveTo(rightPos, 15);
        painterPath.lineTo(rightPos + 10, 20);
        painterPath.lineTo(rightPos, 25);
        painterPath.closeSubpath();
        painter.drawPath(painterPath);

        label->setGeometry(leftPos, 0, width, height);
    }

    // 消息可能非常长，重新调整父元素的宽度
    parent->setFixedHeight(height + 50);
    delete fm;
}
